package com.ityuwen.mengyagushi.order.service.template;

import com.ityuwen.mengyagushi.vo.order.OrderInfoVo;
import com.ityuwen.mengyagushi.vo.order.TradeVo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OrderConfirmTemplate implements ApplicationContextAware {

    private static final Map<String, OrderConfirm> MAP = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(OrderType.class);
        if (CollectionUtils.isEmpty(beanMap)){
            return;
        }
        Collection<Object> beans = beanMap.values();
        beans.forEach(bean -> {
            OrderType orderType = bean.getClass().getAnnotation(OrderType.class);
            MAP.put(orderType.value().type, (OrderConfirm) bean);
        });
    }

    public OrderInfoVo orderConfirm(TradeVo tradeVo){
        return MAP.get(tradeVo.getItemType()).trade(tradeVo);
    }
}
